<template>
  <view style="width: 100%;">
    <u--input
      v-model="currentDateStr" border="none" style="width: 100%;" :placeholder="placeholder"
      suffix-icon="calendar" readonly @click="show = true" />
    <u-datetime-picker
      v-if="show" v-model="currentDate" :show="show" :mode="type"
      :max-date="Number(new Date(maxDate))"
      :min-date="Number(new Date(minDate))"
      :formatter="formatter"
      @cancel="show=false" @confirm="confirm" />
  </view>
</template>

<script>
import {
  parseTime
} from '@/utils'

export default {
  name: 'DatePicker',
  props: {
    modelValue: {
      type: [String, Number],
      default: undefined
    },
    placeholder: {
      type: String,
      default: ''
    },
    pattern: {
      type: String,
      default: '{y}-{m}-{d} {h}:{i}'
    },
    type: {
      type: String,
      default: 'datetime'
    },
    width: {
      type: String,
      default: '100%'
    },
    minDate: {
      type: String,
      default: undefined
    },
    maxDate: {
      type: String,
      default: undefined
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      container: null,
      show: false,
      currentDateStr: undefined,
      currentDate: Number(new Date())
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val, oldVal) {
        if (val) {
          this.currentDate = Number(new Date(this.modelValue.toString().substring(0, 10)))
          this.currentDateStr = parseTime(this.modelValue, this.pattern)
        }
      }
    }
  },
  methods: {
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    confirm(e) {
      this.currentDateStr = this.getTimeStandard(e.value)
      this.$emit('update:modelValue', this.currentDateStr)
      this.show = false
    },
    getTimeStandard(time) {
      var date = new Date(time)
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
      return Y + M + D
    }
  }
}
</script>
